package com.hopes.bizz.risk.transfer.handler;

import com.hopes.bizz.risk.control.entity.RiskControlMeasureEntity;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskConfigEntity;
import com.hopes.bizz.risk.control.entity.RiskUnitEventEntity;
import com.hopes.bizz.risk.control.service.RiskControlMeasureService;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskConfigService;
import com.hopes.bizz.risk.control.service.RiskUnitEventService;
import com.hopes.bizz.risk.transfer.bean.bo.RiskDataBo;
import com.hopes.bizz.risk.transfer.bean.dto.RiskControlMeasuresDto;
import com.hopes.bizz.risk.transfer.constant.RiskErrorType;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.converter.RiskControlMeasuresConverter;
import com.hopes.boss.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 管控措施解析
 * @date 2024/2/4 13:52
 */
@Component
@Slf4j
public class RiskControlMeasuresHandler extends AbstractRiskData<RiskControlMeasuresDto> {
    @Resource
    private RiskUnitEventService riskUnitEventService;
    @Resource
    private RiskControlMeasureService riskControlMeasureService;
    @Resource
    private RiskMeasureTaskConfigService riskMeasureTaskConfigService;

    @Override
    protected void saveRiskData(RiskControlMeasuresDto riskControlMeasuresDto, RiskDataBo riskDataBo) {
        String riskEventId = riskControlMeasuresDto.getRiskEventId();
        RiskUnitEventEntity riskUnitEvent = riskUnitEventService.getByUid(riskEventId);
        if (Objects.isNull(riskUnitEvent) || CommonConstants.STATUS_DEL.equals(riskUnitEvent.getDelFlag())) {
            saveErrorLog(riskControlMeasuresDto, riskDataBo, RiskErrorType.RISK_EVENT_NOT_FOUND);
            return;
        }
        String uid = riskControlMeasuresDto.getId();
        RiskControlMeasureEntity riskControlMeasure = riskControlMeasureService.getByUid(uid);
        RiskControlMeasureEntity riskControlMeasureEntity = RiskControlMeasuresConverter.INSTANCE.toEntity(riskControlMeasuresDto);
        riskControlMeasureEntity.setRiskEventId(riskUnitEvent.getId());
        riskControlMeasureEntity.setRiskUnitId(riskUnitEvent.getRiskUnitId());
        riskControlMeasureEntity.setOrgId(riskDataBo.getOrgId());
        if (Objects.isNull(riskControlMeasure)) {
            // 保存
            riskControlMeasureService.save(riskControlMeasureEntity);
        } else {
            riskControlMeasureEntity.setId(riskControlMeasure.getId());
            riskControlMeasureService.updateById(riskControlMeasureEntity);
        }
    }

    @Override
    public RiskRequestType getRequestType() {
        return RiskRequestType.RISK_CONTROL_MEASURES;
    }
}
